package it.unisalento;

import it.unisalento.appsalento.activity.MainActivity;
import it.unisalento.appsalento.activity.fragment.CalendarioFragment;
import it.unisalento.appsalento.activity.fragment.HomeFragment;
import it.unisalento.appsalento.activity.fragment.RisultatiFragment;
import it.unisalento.appsalento.constants.Constants;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.google.android.gms.gcm.GoogleCloudMessaging;

/**
 * Intent service che gestisce la ricezione delle notifiche push
 * 
 * @author alberto
 *
 */
public class GcmIntentService extends IntentService {

	public static final int NOTIFICATION_ID = 1;
	private NotificationManager mNotificationManager;
	NotificationCompat.Builder builder;

	public GcmIntentService() {
		super("GcmIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
		String messageType = gcm.getMessageType(intent);

		if (!intent.getExtras().isEmpty()) {
			if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
				// Visualizziamo la notifica
				sendNotification(intent);
			}
		}
		// Rilasciamo il wakelock
		GcmBroadcastReceiver.completeWakefulIntent(intent);
	}

	/**
	 * Visualizziamo la notifica
	 * 
	 * @param msg
	 */
	private void sendNotification(Intent intent) {
		String type;
		String title;
		String message;
		Intent launchIntent;
		PendingIntent contentIntent;

		mNotificationManager = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);

		type = intent.getExtras().getString(Constants.NOTIFICATION_EXTRA_TYPE);
		title = intent.getExtras()
				.getString(Constants.NOTIFICATION_EXTRA_TITLE);
		message = intent.getExtras().getString(
				Constants.NOTIFICATION_EXTRA_MESSAGE);

		launchIntent = new Intent(this, MainActivity.class);
		launchIntent.setAction(type);

		contentIntent = PendingIntent.getActivity(this, -1, launchIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle(title)
				.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
				.setContentText(message)
				.setAutoCancel(true)
				.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

		mBuilder.setContentIntent(contentIntent);
		mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
	}
}
